package com.yitongmao.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yitongmao.AppConstancts;
import com.yitongmao.adapter.PlaceOrderActivityAdapter;
import com.yitongmao.bean.LoginHuancunBean;
import com.yitongmao.bean.OrderSuccessBean;
import com.yitongmao.bean.SubmitIndentBean;
import com.yitongmao.common.CallBackListener;
import com.yitongmao.core.cache.ACache;
import com.yitongmao.core.network.service.BaseService;
import com.yitongmao.util.DipUtils;
import com.yitongmao.util.SignUtil;
import com.yitongmao.util.ToastUtils;
import com.yitongmao.yitmfruit.R;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PlaceOrderActivity extends AppCompatActivity {
    @Bind(R.id.mFaPiao)
    AutoLinearLayout mFaPiao;
    @Bind(R.id.idn_back)
    Button idnBack;
    @Bind(R.id.name_tv)
    TextView nameTv;
    @Bind(R.id.phone_tv)
    TextView phoneTv;
    @Bind(R.id.address_tv)
    TextView addressTv;
    @Bind(R.id.platfromName)
    TextView platfromName;
    @Bind(R.id.mPayWay)
    TextView mPayWay;
    @Bind(R.id.mPayType)
    TextView mPayType;
    @Bind(R.id.mFuitSumPrice)
    TextView mFuitSumPrice;
    private String loginId;
    private AutoRelativeLayout mAutoRelativeLayout;
    private LoginHuancunBean loginHuancunBean;
    private int loginId1;
    private String userId;
    private String keyList;
    private String transfer;
    private String all;
    private AutoLinearLayout addressLl;
    private String addressId;
    private String goodsType;
    private Button mSettleAccounts;
    private String shoppingids;
    private String advanceType;
    private ListView mListView;
    private ScrollView mScrollView;
    private View footview;
    private double sumv;
    private String leaveMessage=".";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        immerSion();
        setContentView(R.layout.activity_place_order);
        initView();
        Intent intent = getIntent();
        shoppingids = intent.getStringExtra("ids");
        advanceType = intent.getStringExtra("advanceType");
        ButterKnife.bind(this);
        String submitIndent = ACache.get(PlaceOrderActivity.this).getAsString("submitIndent");
        Gson gson = new Gson();
        //解析查找的缓存并判断
        String loginId = ACache.get(PlaceOrderActivity.this).getAsString("loginId");
        if (loginId != null) {
            loginHuancunBean = gson.fromJson(loginId, LoginHuancunBean.class);
            loginId1 = loginHuancunBean.userInfo.loginId;
            int id = loginHuancunBean.userInfo.id;
            userId = String.valueOf(id);
        }
        SubmitIndentBean submitIndentBean = gson.fromJson(submitIndent, SubmitIndentBean.class);
        //Log.e("zzz", submitIndentBean.toString());
        if (submitIndentBean != null) {
            List<String> keyList1 = submitIndentBean.keyList;
            keyList = String.valueOf(keyList1);
            nameTv.setText(submitIndentBean.address.name);
            phoneTv.setText(submitIndentBean.address.phone);
            addressTv.setText(submitIndentBean.address.provinceName + "" + submitIndentBean.address.cityName + "" + submitIndentBean.address.countryName + "" + submitIndentBean.address.address);
            platfromName.setText(submitIndentBean.platfromName);
            //支付方式
            transfer = submitIndentBean.payMode.get(0).TRANSFER;
            mPayWay.setText(transfer);
            //支付类型
            all = submitIndentBean.payType.get(0).ALL;
            mPayType.setText(all);
            //  mFruitDanjia.setText(submitIndentBean.orderList.get(0).orderGoods.get(0).title);
            //mFruitDanjia.setText("￥" + submitIndentBean.orderList.get(0).orderGoods.get(0).tradePrice);
            for (int i = 0; i < submitIndentBean.orderList.size(); i++) {
                int number = submitIndentBean.orderList.get(i).orderGoods.get(0).number;
                double tradePrice = submitIndentBean.orderList.get(i).orderGoods.get(0).tradePrice;
                sumv = number * tradePrice;
               /* int number = submitIndentBean.orderList.get(i).orderGoods.get(0).number;
                double tradePrice = submitIndentBean.orderList.get(i).orderGoods.get(0).tradePrice;
                sumv = number * tradePrice;*/
            }
            mFuitSumPrice.setText("￥" + sumv);
            int id = submitIndentBean.address.id;
            addressId = String.valueOf(id);
            goodsType = submitIndentBean.goodsType;
            mListView.setAdapter(new PlaceOrderActivityAdapter(PlaceOrderActivity.this, submitIndentBean.orderList));
        }
        setOnClick();
    }
    public void initView() {
        mListView = (ListView) findViewById(R.id.mListView);
        footview = View.inflate(PlaceOrderActivity.this, R.layout.detailsitem, null);
        mListView.addFooterView(footview);
        addressLl = (AutoLinearLayout) findViewById(R.id.have_address_ll);
        mAutoRelativeLayout = (AutoRelativeLayout) findViewById(R.id.mAutoRelativeLayout2);
        mAutoRelativeLayout.setPadding(0, 0, 0, DipUtils.getBottomStatusHeight(this));
        mScrollView = (ScrollView) findViewById(R.id.mScrollView);
    }

    private void setOnClick() {
        mFaPiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PlaceOrderActivity.this, InvoiceActivity.class);
                startActivity(intent);
            }
        });
        mListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mScrollView.requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });
        idnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PlaceOrderActivity.this.finish();
            }
        });
    }

    //沉浸式状态栏
    public void immerSion() {
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.BLACK);
        }
    }

    //支付
    public void intoCloseAnAccount(String userId, String keys, String leaveMessage, String shoppingIds, String payType, String payMode, String totalPrice, String addressId, String goodsType, String invoiceType, String invoiceName, String identifyNumber) {
        //final String replaceid = keys.replace("_1", "");
        Map params = new TreeMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("userId", userId);
        params.put("keys", keys);
        params.put("leaveMessage", leaveMessage);
        params.put("shoppingIds", shoppingIds);
        params.put("payType", payType);
        params.put("payMode", payMode);
        params.put("addressId", addressId);
        params.put("goodsType", goodsType);
        params.put("invoiceType", invoiceType);
        params.put("totalPrice", totalPrice);
        params.put("invoiceName", invoiceName);
        params.put("identifyNumber", identifyNumber);
        params.put("timestamp", timestamp);
        params.put("nonce", nonce);
        params.put("signLogin", SignUtil.signLogin(nonce, timestamp));
        params.put("loginId", String.valueOf(loginId1));
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.closeAnAccount, params, new CallBackListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(Object result) {
                String string = (String) result;
                Log.e("zzz", result.toString());
                Gson gson = new Gson();
                OrderSuccessBean orderSuccessBean = gson.fromJson(string, OrderSuccessBean.class);
                if (orderSuccessBean.result.state.equals("1")) {
                    ACache.get(PlaceOrderActivity.this).put("submitsuccess", string, 30 * 24 * 60 * 60 * 60);
                    Intent intent = new Intent(PlaceOrderActivity.this, IndentSuccessActivity.class);
                    startActivity(intent);
                    PlaceOrderActivity.this.finish();
                }
                ToastUtils.showShort(PlaceOrderActivity.this, "成功");
            }
            @Override
            public void onFail(Object result) {
                Log.e("Object", result.toString());
                ToastUtils.showShort(PlaceOrderActivity.this, "失败");
            }
        });
    }
    @OnClick({R.id.address_ll, R.id.mSettleAccounts})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.address_ll:
                Intent intent1 = new Intent(PlaceOrderActivity.this, AddAddressActivity.class);
                startActivity(intent1);
                ToastUtils.showShort(PlaceOrderActivity.this, "11111111111");
                break;
            case R.id.mSettleAccounts:
                // String leaveMessage = mLuiyan.getText().toString().trim();
                Intent intent = getIntent();
                String invoiceType = intent.getStringExtra("invoiceType");
                String invoiceName = intent.getStringExtra("invoiceName");
                String identifyNumber = intent.getStringExtra("identifyNumber");
              /*  StringBuffer stringBuffer=new StringBuffer();
                //stringBuffer.append(stringBuffer.append(keyList).append(","));
                String substringkeyList = stringBuffer.toString().substring(0, (stringBuffer.toString().length() - 2));*/
                String substringkeyList = keyList.substring(1, keyList.length() - 1);
                //ToastUtils.showShort(PlaceOrderActivity.this,""+keyList);
                if (leaveMessage.equals("")) {
                    leaveMessage = ".";
                }
                if (all.equals("全款")) {
                    all = "ALL";
                }
                if (transfer.equals("公司转账")) {
                    transfer = "TRANSFER";
                }
                intoCloseAnAccount(userId, substringkeyList, leaveMessage, shoppingids, all, transfer, String.valueOf(sumv), addressId, advanceType, invoiceType, invoiceName, identifyNumber);
                break;
        }
    }

}
